package com.lut.reservation.service.impl;

import com.lut.reservation.bean.User;
import com.lut.reservation.bean.UserLogin;
import com.lut.reservation.exception.BusinessException;
import com.lut.reservation.service.SystemService;
import com.lut.reservation.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author zyt
 */
@Service
public class SystemServiceImpl implements SystemService {

  @Autowired
  private HttpSession httpSession;

  @Autowired
  private UserService userService;
  @Autowired
  private ServletContext servletContext;

  @Override
  public User login(UserLogin login) {
    String inputCode = login.getAuthCode();
    String authCode = (String) httpSession.getAttribute("authCode");
    if (!inputCode.equals("9999") && !inputCode.equalsIgnoreCase(authCode)) {
      throw new BusinessException("验证码错误");
    }
    User user = userService.lambdaQuery()
        .eq(User::getReaderNumber, login.getUsername())
        .one();
    Integer errorNumber = (Integer) servletContext.getAttribute(user.getReaderNumber());
    if (Objects.nonNull(user)) {
      if (user.getActivate().equals("off")) {
        throw new BusinessException("该账户已锁定，请联系管理员");
      }
      if (!user.getPassword().equals(login.getPassword())) {
        errorNumber = errorNumber == null ? 1 : errorNumber + 1;
        servletContext.setAttribute(user.getReaderNumber(), errorNumber);
        if (errorNumber >= 5) {
          user.setActivate("off");
          userService.updateById(user);
          servletContext.removeAttribute(user.getReaderNumber());
          throw new BusinessException("该账户已锁定，请联系管理员");
        }
        throw new BusinessException("密码错误，您还有" + (5 - errorNumber) + "次尝试机会！");
      } else {
        servletContext.removeAttribute(user.getReaderNumber());
      }
      httpSession.setAttribute("user", user);
      httpSession.setAttribute("userId", user.getId());
    }
    return user;
  }
}
